<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\admin\model;

use api\common\model\CommonModel;
use api\admin\model\BandToiletModel;
use api\admin\model\ToiletFlowModel;

class ToiletSensorModel extends CommonModel
{
    // 可查询字段
    // protected $visible = [
    //     'id', 'start_time', 'end_time', 'man_num', 'woman_num','flow_num','titile','position','create_time',
    // ];
    //模型关联方法
    // protected $relationFilter = ['articles'];

    /**
     * 基础查询
     */
    // protected function base($query)
    // {
    //     $query->alias('toilet')->where('toilet.status', 1);
    // }
    /**
     * 关联
     * @return $this
     */
    // public function articles()
    // {
    //     return $this->belongsToMany('PortalPostModel','portal_tag_post','post_id','tag_id');
    // }



    /**
     * [DetailsOther 获取传感器数据的平均值]
     * @Author   HUI
     * @DateTime 2019-01-16
     * @version  [version]
     * @param    [type]     $mac      [description]
     * @param    [type]     $type     [description]
     * @param    [type]     $userTime [description]
     * @param    [type]     $dateTime [description]
     */
    public function DetailsOther($mac, $type,$userTime,$dateTime)
    {

        // print_r($mac);exit();
        // $BandToilet = new BandToiletModel();

        switch ($type) {
            case '3':
                return $this->getSensorYearDetails($mac,$userTime,$dateTime);
                break;
            case '2':
                return $this->getSensorMonthDetails($mac,$userTime,$dateTime);
                break;
            default:
                return $this->getSensorDefaultDetails($mac,$userTime,$dateTime);
                break;
        }
    }


    /**
     * [getSensorYearDetails 获取年度数据]
     * @Author   HUI
     * @DateTime 2019-01-16
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getSensorYearDetails($mac,$userTime,$dateTime)
    {
         $result = $this
            ->field('FROM_UNIXTIME(create_time, "%m-%d") as times,avg(h2s) as avg_h2s,avg(nh3) as avg_nh3,avg(humidity) as avg_humidity,avg(temperature) as avg_temperature')
            ->whereTime('create_time',  'between', [$userTime.'-1-1', $userTime.'-12-31'])
            ->where('master_mac',  $mac)
            ->group('times')
            ->select()->toArray();
        return $this->checkSensorRes($result,$dateTime);
    }

    /**
     * [getSensorMonthDetails]
     * @Author   HUI
     * @DateTime 2019-01-16
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getSensorMonthDetails($mac,$userTime,$dateTime)
    {

        $ToiletFlow = new ToiletFlowModel();
        $tmp = $ToiletFlow->getMonth($userTime);
        $result = $this
            ->field('FROM_UNIXTIME(create_time, "%m-%d") as times,avg(h2s) as avg_h2s,avg(nh3) as avg_nh3,avg(humidity) as avg_humidity,avg(temperature) as avg_temperature')
            ->whereTime('create_time',  'between', [strtotime($tmp['start_time']), strtotime($tmp['end_time'])])
            ->where('master_mac',  $mac)
            ->group('times')
            ->select()->toArray();

        return $this->checkSensorRes($result,$dateTime);
    }


    /**
     * [getSensorDefaultDetails 获取7/30天的数据]
     * @Author   HUI
     * @DateTime 2019-01-16
     * @version  [version]
     * @param    [type]     $mac      [description]
     * @param    [type]     $ids      [description]
     * @param    [type]     $userTime [description]
     * @param    [type]     $dateTime [description]
     * @return   [type]               [description]
     */
    public function getSensorDefaultDetails($mac,$userTime,$dateTime)
    {
        $result = $this->field('FROM_UNIXTIME(create_time, "%m-%d") as times,avg(h2s) as avg_h2s,avg(nh3) as avg_nh3,avg(humidity) as avg_humidity,avg(temperature) as avg_temperature')->whereTime('create_time', -count($dateTime) . ' days')
            ->where('master_mac',  $mac)
            ->group('times')
            ->select()->toArray();

        return $this->checkSensorRes($result,$dateTime);
    }


    /**
     * [checkSensorRes 出路查询数据并返回]
     * @Author   HUI
     * @DateTime 2019-01-16
     * @version  [version]
     * @param    [type]     $result [description]
     * @return   [type]             [description]
     */
    public function checkSensorRes($data,$dateTime)
    {


        $dataTmp = $this->arraySensorToEasy($data);
        $detailsNum['H2S'] = [];
        $detailsNum['NH3'] = [];
        $detailsNum['humidity'] = [];
        $detailsNum['temperature'] = [];
        foreach ($dateTime as $key => $value) {
            //
            $detailsNum['H2S'][] = isset($dataTmp[$value]) ? round($dataTmp[$value]['avg_h2s'],2):0;
            $detailsNum['NH3'][] = isset($dataTmp[$value]) ? round($dataTmp[$value]['avg_nh3'],2):0;
            $detailsNum['humidity'][] = isset($dataTmp[$value]) ? round($dataTmp[$value]['avg_humidity'],2):0;
            $detailsNum['temperature'][] = isset($dataTmp[$value]) ? round($dataTmp[$value]['avg_temperature'],2):0;
        }

        // print_r($detailsNum);exit();
        return $detailsNum;


        // print_r($result);exit();

        // $num = ["avg_h2s"=>0,"avg_nh3"=>0,"avg_humidity"=>0,"avg_temperature"=>0];
        // if (isset($result[0]) && !empty($result[0])) {
        //     $num = [
        //         'avg_h2s' => isset($result[0]['avg_h2s']) ? $result[0]['avg_h2s']:0,
        //         'avg_nh3' => isset($result[0]['avg_nh3']) ? $result[0]['avg_nh3']:0,
        //         'avg_humidity' => isset($result[0]['avg_humidity']) ? $result[0]['avg_humidity']:0,
        //         'avg_temperature' => isset($result[0]['avg_temperature']) ? $result[0]['avg_temperature']:0
        //     ];
        // }
        // return $num;
    }


    /**
     * [arrayToEasy 处理数组]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $data [description]
     * @return   [type]           [description]
     */
    public function arraySensorToEasy($data)
    {
        $dataTmp = [];
        if (count($data)) {
            foreach ($data as $key => $value) {
                $dataTmp[$value['times']] = $value;
            }
        }
        return $dataTmp;
    }

    
    /**
     * [getToiletFields 获取单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function getToiletSensorFields($id, $fields = '*')
    {
        if (is_array($id)) {
            return $this->field($fields)->where($id)->find();

        } else {
            return $this->field($fields)->where('id', $id)->find();
        }

    }

    /**
     * [getToiletFields 更新单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function updateToiletSensorFields($id, $update = [])
    {

        if (is_array($id)) {
            return $this->where($id)->update($update);
        } else {
            return $this->where('id', $id)->update($update);
        }
    }
    

}
